package com.usian.comment.service.impl;

import com.usian.comment.feign.UserFeign;
import com.usian.comment.repository.ApCommentLikeRepository;
import com.usian.comment.repository.ApCommentRepository;
import com.usian.comment.service.ApCommentService;
import com.usian.common.aliyun.GreeTextScan;
import com.usian.model.comment.dtos.CommentDto;
import com.usian.model.comment.dtos.CommentLikeDto;
import com.usian.model.comment.dtos.CommentSaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentLike;
import com.usian.model.comment.vo.ApCommentVo;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ApCommentServiceImpl implements ApCommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ApCommentRepository apCommentRepository;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private GreeTextScan greeTextScan;

    @Autowired
    private ApCommentLikeRepository apCommentLikeRepository;

    private static final int DEFAULT_SIZE =10;

//    @Override
//    public ResponseResult saveComment(CommentSaveDto dto) {
//        if (dto.getArticleId() == null || StringUtils.isEmpty(dto.getContent())) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
//        }
//        if (dto.getContent().length() > 140) {
//            return ResponseResult.errorResult(500, "评论不能超过140字");
//        }
//        ApUser user = AppThreadLocalUtils.getUser();
//        if (user == null || user.getId() == null) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
//        }
//
//        ApUser userInfo = userFeign.getUserById(user.getId());
//
//        if (userInfo == null) {
//            return ResponseResult.errorResult(500, "查询不到用户信息！");
//        }
//
//        boolean scanResult = handleTextInAliyun(dto.getContent());
//        if (!scanResult){
//            return ResponseResult.errorResult(500, "评论内容违规，不能发布！");
//        }
//
//        ApComment apComment=new ApComment();
//        apComment.setAuthorId(userInfo.getId());
//        apComment.setAuthorName(userInfo.getName());
//        apComment.setImage(userInfo.getImage());
//        apComment.setEntryId(dto.getArticleId());
//        apComment.setType((short)0);
//        apComment.setContent(dto.getContent());
//        apComment.setLikes(0);
//        apComment.setReply(0);
//        apComment.setFlag((short)0);
//        apComment.setCreatedTime(new Date());
//        apComment.setUpdatedTime(new Date());
//        ApComment saveResult = apCommentRepository.save(apComment);
//
//        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
//    }


    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //1.检查参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getContent() != null && dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "评论内容不能超过140字");
        }

        //2.判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.安全过滤,自行实现

        //4.保存评论
        ApUser apUser = userFeign.getUserById(user.getId());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误");
        }
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);
        mongoTemplate.insert(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult likeComment(CommentLikeDto dto) {
        //参数校验

        if(StringUtils.isEmpty(dto.getCommentId())
                 || dto.getOperation()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getOperation().shortValue()!=0 && dto.getOperation().shortValue()!=1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //是否登录
        ApUser user=AppThreadLocalUtils.getUser();
        if (user==null || user.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApComment apComment = apCommentRepository.findById(dto.getCommentId()).get();

        if(dto.getOperation()==0){
            //点赞功能
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setOperation(dto.getOperation());
            apCommentLikeRepository.save(apCommentLike);

            apComment.setLikes(apComment.getLikes()+1);
            apCommentRepository.save(apComment);
        }else{
            //取消点赞
            apComment.setLikes(apComment.getLikes()>0 ? apComment.getLikes()-1 : 0);
            apCommentRepository.save(apComment);
            apCommentLikeRepository.deleteByAuthorIdAndCommentId(user.getId(),dto.getCommentId());

        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);


    }

    @Override
    public ResponseResult loadCommentList(CommentDto dto) {
        //参数校验
        if (dto.getArticleId() ==null || dto.getMinDate()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 当前文章id进行检索，按照创建时间倒叙，分页查询 10条
        PageRequest pageRequest = PageRequest.of(0, DEFAULT_SIZE);
        List<ApComment> apCommentList =
                apCommentRepository.findByEntryIdOrderByCreatedTimeDesc(dto.getArticleId(), pageRequest);


        //用户未登录 直接返回数据
        ApUser user=AppThreadLocalUtils.getUser();
        if (user==null || user.getId()==null){
            return ResponseResult.okResult(apCommentList);
        }

        // 用户已登陆  需要判断当前用户点赞了哪些评论

        List<String> commentIdList =
                apCommentList.stream().map(x -> x.getId()).collect(Collectors.toList());
        List<ApCommentLike> likeList =
                apCommentLikeRepository.findByCommentIdInAndAuthorId(commentIdList, user.getId());

        List<ApCommentVo> resultList = new ArrayList<>();

        if (apCommentList !=null && likeList !=null){
            apCommentList.forEach(x ->{
                ApCommentVo vo=new ApCommentVo();
                BeanUtils.copyProperties(x,vo);
                for (ApCommentLike like : likeList) {
                    if (x.getId().equals(like.getCommentId())){
                        vo.setOperation((short)0);
                        break;
                    }
                }
                resultList.add(vo);
            });
            return ResponseResult.okResult(resultList);
        }else{
            return ResponseResult.okResult(apCommentList);
        }

    }


    private boolean handleTextInAliyun(String text) {
        boolean flag = true;

        try {
            Map map = greeTextScan.greeTextScan(text);

            String suggesttion = (String) map.get("suggesttion");
            if (!suggesttion.equals("pass")) {
                if (suggesttion.equals("block") || suggesttion.equals("review")) {
                    flag = false;
                }

            }
            } catch(Exception e){
                e.printStackTrace();
                log.error("文本审核出现异常，信息如下：{}", e.getMessage());
                flag = false;
            }

            return flag;
        }
    }
